/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.rpc_connection;

import java.io.IOException;

import it.gashale.jacolib.connection.Connection;
import it.gashale.jacolib.core.JacolibError;
import it.gashale.jacolib.core.ProtocolError;
import it.gashale.jacolib.rpc.ExecHandler;
import it.gashale.jacolib.rpc.QuitHandler;
import it.gashale.jacolib.rpc.RPCChannel;

public class RPCConnection {
	private Connection connection;
	private RPCChannel channel;
	
	public RPCConnection(Connection con, RPCChannel channel) {
		connection=con;
		this.channel=channel;
		channel.setExecHandler(new ExecHandler() {
			public String handles(String req) throws JacolibError {
				connection.send_request(req);
				String res=loop_until_response();
				return res;
			}
		});
		channel.setQuitHandler(new QuitHandler() {
			public void handles() throws JacolibError {
				try {
					connection.close();
				} catch (IOException e) {
					throw new JacolibError(e.getMessage());
				}
			}
		});
	}
	public RPCChannel getRPCChannel() {
		return channel;
	}
	
	public String step() throws JacolibError {
		String r = connection.receive();
		if(r.equals("res")) {
			
		} else if(r.equals("req")) {
			try {
				connection.send_response(channel.getRPCServerStub().exec(connection.getStr()));
			} catch(JacolibError e) {
				try {
					connection.send_fatalerror_and_quit("Remote error: "+e.getMessage());
				} catch (IOException e1) {
				}
				throw e;
			}
		} else if (r.equals("fatal-error")) {
			throw new ProtocolError(connection.getStr());
		}	
		return r;
	}
	public void loop_until_quit() throws JacolibError {
		while(true) {
			String r=step();
			if(r.equals("close")) {
				channel.quit_p();
				return;
			}
		}
	}
	protected String loop_until_response() throws JacolibError {
		while(true) {
			String r=step();
			if(r.equals("res")) {
				return connection.getStr();
			} else if (r.equals("close")){
				throw new ProtocolError("connection was unexpectedly closed.");
			}
		}
	}
	public void quit() throws JacolibError {
		channel.quit();
	}
}
